import React from "react";
export default class jumpingBall extends React.Component {
  constructor(props) {
    super(props)
    this.ballWindow = React.createRef();
  }
  state = {
    x: 0,
    y: 0,
    speed: 0,
    direction: null,
    timeOutConstructor: null
  }
  componentDidMount() {
    this.playAnimation();
    document.addEventListener("keydown", this.ballMobile.bind(this));
    document.addEventListener("keyup", this.stopBallMobile.bind(this));
    this.setState({
      x: this.ballWindow.current.offsetWidth * 0.20
    })
  }
  playAnimation() {
    this.setState({
      timeOutConstructor: setInterval(() => {
        this.setState({
          speed: this.state.speed + 0.04
        });
        this.animationFunc();
      }, 10)
    })
  }
  stopBallMobile() {
    this.setState({
      direction: null
    })
  }
  ballMobile(event) {
    if (event.keyCode === 39) {
      this.setState({
        direction: "right"
      })
    } else if (event.keyCode === 37) {
      this.setState({
        direction: "left"
      })
    }
  }
  setCoordinate() {
    this.setState({
      y: 235 * Math.sin(this.state.speed) + 300,
    })
    switch (this.state.direction) {
      case "left":
        this.setState({
          x: this.state.x - 4
        })
        break;
      case "right":
        this.setState({
          x: this.state.x + 4
        })
        break;
      default:
        break;
    }
  }
  animationFunc() {
    this.setCoordinate();
    if (this.state.y >= 420) {
      this.setState({
        y: 420,
        speed: this.state.speed + 0.5
      });
    }
  }
  tick(event) {
    console.log(231231)
    this.state.update();
  }
  componentWillUnmount() {
    document.removeEventListener("keydown", this.ballMobile);
    document.removeEventListener("keyup", this.stopBallMobile);
    clearInterval(this.state.timeOutConstructor);
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    return (
      <div
        ref={this.ballWindow}
        style={{
          "width": "100%",
          "height": "100%",
          "textAlign": "center",
          "position": "relative",
          "backgroundColor": "#8fea7d"
        }}>
        <img
          alt="皮球"
          style={{
            "position": "absolute",
            "top": this.state.y + "px",
            "left": this.state.x + "px"
          }}
          src="/componentListPageAssets/bounceAnimat/ball.png"></img>
      </div>
    )
  }
};